<template>
	<view class="login">
		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<image :src="logoImage"></image>
			</view>
			<!-- 主体表单 -->
			<view class="main">
				<tInput v-model="username" type="text" placeholder="用户名/邮箱" :focus="isFocus"></tInput>
				<tInput v-model="password" type="password" placeholder="密码"></tInput>
			</view>
			<tButton class="wbutton" text="登 录" :rotate="isRotate" @click="login"></tButton>



			<!-- 底部信息 -->
			<view class="footer">
				<navigator url="forget" open-type="navigate">找回密码</navigator>
				<text>|</text>
				<navigator url="register" open-type="navigate">注册账号</navigator>
			</view>
		</view>
	</view>
</template>

<script>
	let _this;
	import tInput from '@/components/tally-login/tally-input.vue'
	import tButton from '@/components/tally-login/tally-button.vue'

	export default {
		components: {
			tInput,
			tButton,
		},
		data() {
			return {
				// logo图片
				logoImage: require("@/static/logo.png"),
				username: '', 	 // 用户名
				password: '', 	 // 密码
				isRotate: false, // 是否加载旋转
				isFocus: true 	 // 是否聚焦
			};
		},
		// 进入页面后执行
		mounted() {
			_this = this;
		},
		// 页面加载传递值
		onLoad(options) {
			if (options.username) {
				this.username = options.username
			}
			if (options.password) {
				this.password = options.password
			}
		},
		methods: {
			// 登录
			login(e) {
				//判断是否加载中，避免重复点击请求
				if (this.isRotate) {
					return false;
				}
				// 加载旋转
				_this.isRotate = true
				// 请求信息封装
				let data = {
					username: _this.username,
					password: _this.password,
					flag: 1
				}
				this.$api({
					method: 'post',
					url: '/user/login',
					data: data
				}).then(res => {
					if (res.code == 0) {
						// 存入store和本次缓存中
						this.$store.commit("user", res.data);
						this.$store.commit("token", res.data.token);
						uni.setStorageSync("user", res.data);
						uni.setStorageSync("token", res.data.token);
						this.book();
						this.$u.toast(res.msg);
						// 关闭旋转
						_this.isRotate = false
						// 进入首页
						uni.switchTab({
							url: "/pages/index/index",
							fail(err) {
								console.log(err)
							}
						})
					} else {
						// 关闭旋转
						_this.isRotate = false
						// 错误提示
						this.$u.toast(res.msg);
					}
				}).catch(err => {
					// 关闭旋转
					_this.isRotate = false
					console.log(err)
					this.$u.toast("网络连接失败");
				});
			},
			// 获取账本信息
			book() {
				this.$api({
					method: 'post',
					url: '/system/book/list',
					data: {
						"state": 1
					}
				}).then(res => {
					if (res.code == 0 && res.total > 0) {
						// 缓存默认账本信息
						this.$store.commit("book", res.rows[0]);
						uni.setStorageSync("book", res.rows[0]);
					} 
				}).catch(err => {});
			}
		}
	}
</script>

<style>
	@import url("@/components/tally-login/css/icon.css");
	@import url("./css/main.css");
</style>